package com.example;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Date;

public class SoftReferenceTest {

    public static class Car{

        @Override
        public String toString() {
            return "这是一辆车";
        }
    }

    // 通过JVM参数"-Xmx1024K"把最大堆内存设置为1024K
    // 这样能才能比较快地看到softReference所引用的car被垃圾回收器回收
    public static void main(String[] args) throws InterruptedException {

        ReferenceQueue referenceQueue = new ReferenceQueue();
        SoftReference<Car> softReference = new SoftReference<>(new Car(), referenceQueue);

        System.out.println("referenceQueue.poll():" + referenceQueue.poll());

        StringBuilder stringBuilder = new StringBuilder();

        while (true){

            Date date = new Date();
            if(softReference.get() != null){
                System.out.println(date +  " - softReference所引用的对象（car）还没死");
                System.out.println("referenceQueue.poll(): " + referenceQueue.poll());

                // 往stringBuilder中塞一些数据以减少可用空间
                stringBuilder.append("占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存占用堆内存");
                // 睡一会避免循环太快导致GC来不及运行程序就挂掉了
                Thread.sleep(100);
            }else {
                System.out.println(date + "  - car 被构成回收了");
                SoftReference temp = (SoftReference) referenceQueue.poll();
                System.out.println("referenceQueue.poll(): " + temp );
                System.out.println("referenceQueue.poll() == softReference ?:" + (temp == softReference) );
                break;
            }
        }
        System.out.println(stringBuilder);
    }
}
